'use strict';

import Base from './base.js';

import fs from 'fs';
import path from 'path';


export default class extends Base {
    /**
     * index action
     * @return {Promise} []
     */
    async indexAction(that){
        //这里的 key 需要和 form 表单里的 name 值保持一致
        var file = think.extend({}, this.file('file'));
        if(!file){
            return that.fail("上传失败");
        }
        var filepath = file.path;

        //文件上传后，需要将文件移动到项目其他地方，否则会在请求结束时删除掉该文件
        var uploadPath = think.RESOURCE_PATH + '\\static\\upload';
        think.mkdir(uploadPath);
        var basename = path.basename(filepath);
        fs.renameSync(filepath, uploadPath + '\\' + basename);
        file.path = uploadPath + '\\' + basename;

        var result = {
            "code": -1
            , "msg": '上传失败'
        };
        //校验是否成功上传
        if(think.isFile(file.path)){
            let domain = think.DOMAIN;
            let path = `${domain}/static/upload/${basename}`;
            result['code'] = 0;
            result['msg'] = '上传成功';
            result['data'] = {
                src:path,
                title:file.originalFilename
            };
        }
        that.json(result);
    }
}